package com.zhaogang.transactionManagerDemo.service.impl;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;

import com.zhaogang.transactionManagerDemo.entity.SystemLog;
import com.zhaogang.transactionManagerDemo.mapper.AccountMapper;
import com.zhaogang.transactionManagerDemo.service.AccountTransactionService;

@Service("AccountTransactionServiceSpringTxImpl")
public class AccountTransactionServiceSpringTxImpl implements AccountTransactionService {
	
	@Autowired
	private PlatformTransactionManager tm;
	@Autowired
	private AccountMapper accountMapper;

	private static Logger logger = LoggerFactory.getLogger(AccountTransactionServiceSpringTxImpl.class);
	
	@Override
	public int updateBalanceByAccountNo(String accountNo, BigDecimal amount) {
		return 0;
	}

	@Override
	public void transferSimple(String fromAccountNo, String toAccountNo, BigDecimal amount) {
		TransactionDefinition td = new DefaultTransactionDefinition();
		TransactionStatus ts = tm.getTransaction(td);
		try {
			int affectCount = accountMapper.updateBalanceByAccountNo(toAccountNo, amount);
			Assert.isTrue(affectCount == 1, String.format("账户[%s]不存在或者余额不足", toAccountNo));
			affectCount = accountMapper.updateBalanceByAccountNo(fromAccountNo, amount.negate());
			Assert.isTrue(affectCount == 1, String.format("账户[%s]不存在或者余额不足", fromAccountNo));
			tm.commit(ts);
		} catch (Exception e) {
			tm.rollback(ts);
		}		
	}

	@Override
	public void transferSimpleNoTrans(String fromAccountNo, String toAccountNo, BigDecimal amount) {

	}

	@Override
	public void transfer(String fromAccountNo, String toAccountNo, BigDecimal amount) {
		
	}

	@Override
	public SystemLog addLog(String topic, String tableName, Object old, Object now) {
		return null;
	}

	@Override
	public void transferException(String fromAccountNo, String toAccountNo, BigDecimal amount) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
